<?php
/**
 *  留存统计
 *  留存是计算 昨天的人数 昨天在的人今天还在的人数
 *  留存率    昨天在的人今天还在的人数/昨天的人数
 * @author: jiangyong<jiangyong.go@qq.com>
 * @Date: 2023/5/26 16:01
 */

$filename1 = 'origin/城主5月31日打点.csv';
$filename2 = 'origin/城主6月1日打点.csv';

$name1 = getFilename($filename1);
$name2 = getFilename($filename2);

$index_key  = 'momo_id';
$momoIds = getCsvData($filename1, $index_key);

$momoIds = array_keys($momoIds);
$count = count($momoIds);


$newMomoIds = getCsvData($filename2, $index_key);

$newMomoIds = array_keys($newMomoIds);
$newCount = count($newMomoIds);

//var_dump($newMomoIds);

$diffIds = array_diff($newMomoIds, $momoIds);
$diffCount = count($diffIds);
$intersect = array_intersect($newMomoIds, $momoIds);
$intersectCount = count($intersect);

$per = $intersectCount / $count * 100;

//统计留存分类
$momoIdLow = [];
$momoIdHight = [];
foreach ($intersect as $momoId) {
    if (5 > substr($momoId, -1)) {
        $momoIdLow[] = $momoId;
    } else{
        $momoIdHight[] = $momoId;
    }
}
//var_dump($momoIdLow, $momoIdHight);
$intersectLowCount = count($momoIdLow);
$intersectHigntCount = count($momoIdHight);

//var_dump($count, $newCount, $intersectCount,  $per, $intersectLowCount, $intersectHigntCount, $diffCount);

$per = sprintf("%0.2f", $per);
$str = <<<END
{$name2}统计{$name1}留存
$name1           $count
$name2           $newCount
留存              $intersectCount  
留存momoID尾号0-4  $intersectLowCount
留存momoID尾号4-9  $intersectHigntCount
留存率             $per
END;

echo $str;


$saveData = [
    ["{$name2}统计{$name1}留存"],
    [$name1,$count],
    [$name2,$newCount],
    ['留存',$intersectCount],
    ['留存momoID尾号0-4',$intersectCount],
    ['留存momoID尾号4-9',$intersectHigntCount],
    ['留存率',$per],
];
$wfile = "dest/{$name1}统计{$name2}留存.csv";

/*foreach ($saveData as $row) {
    printf("%-30s%s\n", $row[0], $row[1]??'');
}*/

saveCsvData($wfile, $saveData);

function saveCsvData($file, $list)
{
    $fp = fopen($file, 'w');
    foreach ($list as $id => $fields) {
        fputcsv($fp, $fields);
    }
    fclose($fp);
}


function getCsvData($filename, $index_key = null)
{
    $list = [];
    $row = 1;
    if (($handle = fopen($filename, "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000)) !== FALSE) {
            $num = count($data);
            //echo "<p> $num fields in line $row: <br /></p>\n";
            if (1 == $row) {
                $fields = $data;
                $row++;
                continue;
            }

            $info = [];
            for ($c=0; $c < $num; $c++) {
                $info[$fields[$c]] = $data[$c];
            }
            if ($index_key) {
                if (!isset($info[$index_key])) var_dump($info);
                $list[$info[$index_key]] = 0;
            } else {
                $list[] = $info;
            }
            $row++;

        }
        fclose($handle);
    }
    return $list;
}


function getFilename($filename)
{
    $path_parts = pathinfo($filename);
    return  $path_parts['filename'];
}